<template>
  <div class="cascader-search">
    <el-cascader
      :value="value"
      :props="cascadeProps"
      :options="options"
      :placeholder="placeholder"
      :show-all-levels="(!isMulti && displayMode != 1) || displayMode == 2"
      clearable
      @change="changeValue"
    />
  </div>
</template>

<script>
import { defineComponent } from 'vue';
import i18n from '@src/locales';

export default defineComponent({
  name: 'cascader-search',
  props: {
    field: {
      type: Object,
      default: null,
    },
    placeholder: {
      type: String,
      default: i18n.t('common.placeholder.select'),
    },
    value: {
      type: [String, Array],
      default: '',
    },
  },
  emits: ['update'],
  setup(props, { emit }) {
    // 是否多选
    const isMulti = !!props.field?.setting?.isMulti;
    // 选项显示模式
    const displayMode = props.field?.setting?.displayMode;
    const checkStrictly =  !!(props.field?.setting?.checkStrictly ?? true); // 需求默认允许选择任意层级
    const cascadeProps = {
        value: 'value',
        label: 'value',
        children: 'children',
        multiple: isMulti,
        checkStrictly: checkStrictly, // 支持任意一级选择
    };

    function disposeOption(item) {
      const _item = {
        label: item.label ?? item.value,
        value: item.value,
      }
      if (item.children?.length) {
        _item.children = item.children.map(disposeOption);
      }
      return _item;
    }
    const options = (props.field?.setting.dataSource || []).map(disposeOption)

    // 改变值
    function changeValue(value) {
      emit('update', value);
    }

    return {
      cascadeProps,
      options,
      isMulti,
      displayMode,
      changeValue,
    };
  },
});
</script>

<style></style>
